﻿using System.IO;
using System.Web.Mvc;
using Orchard.UI.Resources;
using System.Linq;

namespace Eking.Framework
{
    public static class Extenstions
    {
        public static void DefineStyleSimple(this Orchard.UI.Resources.ResourceManifest manifest, params string[] styles)
        {
            foreach (var style in styles)
            {
                manifest.DefineStyle(style).SetUrl(style);
            }
        }

        public static void DefineScriptSimple(this Orchard.UI.Resources.ResourceManifest manifest, params string[] scripts)
        {
            foreach (var script in scripts)
            {
                manifest.DefineScript(script).SetUrl(script);
            }
        }

        public static void RequireSimple(this ResourceRegister register, params string[] items)
        {
            foreach (var item in items)
            {
                register.Require(item).AtHead();
            }
        }

        public static void RequireSet(this Orchard.Mvc.ViewEngines.Razor.WebViewPage<dynamic> webpage, string set)
        {
            var query = from i in ResourceManifest.RequireSets[set][0].Split(',')
                        where !string.IsNullOrEmpty(i.Trim())
                        select i.Trim();
            webpage.Style.RequireSimple(query.ToArray());
            query = from i in ResourceManifest.RequireSets[set][1].Split(',')
                    where !string.IsNullOrEmpty(i.Trim())
                    select i.Trim();
            webpage.Script.RequireSimple(query.ToArray());
        }



        public static string RenderPartialViewToString(this Controller controller)
        {
            return RenderPartialViewToString(null, null);
        }

        public static string RenderPartialViewToString(this Controller controller, string viewName)
        {
            return controller.RenderPartialViewToString(viewName, null);
        }

        public static string RenderPartialViewToString(this Controller controller, object model)
        {
            return RenderPartialViewToString(null, model);
        }

        public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

            controller.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
